import { useState, useImperativeHandle, forwardRef } from 'react';
import styles from './index.less';
import { Tabs, Table, Spin, Drawer } from 'antd';
import { tableLocale } from '@/tool/components/PageEmpty';
import moment from 'moment';
import { connect } from 'umi';

import { TRMessage } from '#/components';
import { HttpCode } from '#/utils/contacts';
import { operateLogModal, selectedCircle, upHide, downShow } from '@/assets';
import { fetchOperateLogs, fetchPrograms } from '@/pages/Tianji/RollingBatch/services';

import {
  TRADE_STRATEGY,
  SUBMIT_TYPE,
  LOG_TYPE,
  PROGARM_STATUS,
  LOG_TYPE_CN,
} from '../../constant/enums';
import messageConstant from '../../constant/message';
import { clone } from '../../utils';

const { TabPane } = Tabs,
  { Column } = Table;

function OperateLogModal({ currentSequenceId, currentProgramId }, ref) {
  useImperativeHandle(ref, () => ({ initHandle }));

  const [operateLogList, setOperateLogList] = useState([]),
    [tabActiveKey, setTabActiveKey] = useState(),
    [showOperateLog, setShowOperateLog] = useState(false),
    [loading, setLoading] = useState(false),
    [programList, setProgramList] = useState([]);

  const initHandle = () => {
    setShowOperateLog(true);
    // 获取全部方案列表
    fetchProgramsAll();
    // 获取方案日志
    fetchOperateLogsFunc(currentProgramId);
  };
  /**
   * 获取方案列表
   */
  const fetchProgramsAll = () => {
    fetchPrograms(currentSequenceId, true).then(({ statusCode, message, data }) => {
      if (statusCode === HttpCode.SUCCESS) {
        setProgramList(data?.programList || []);
      } else {
        TRMessage.error(message || messageConstant.FETCH_PROGRAM_LIST_DEFAULT_ERROR_MESSAGE);
      }
    });
  };

  /**
   * 获取方案的日志列表
   * @param {*} programId
   */
  const fetchOperateLogsFunc = (programId) => {
    setTabActiveKey(programId);
    setLoading(true);
    fetchOperateLogs(programId).then(({ statusCode, message, data }) => {
      setLoading(false);
      if (statusCode === HttpCode.SUCCESS) {
        setOperateLogList(data?.operateLogList);
      } else {
        TRMessage.error(message || messageConstant.FETCH_PROGRAM_LOGS_ERROR_MESSAGE);
      }
    });
  };

  const changeShowDetail = (index) => {
    let data = clone(operateLogList);
    data[index].showDetail = !data[index].showDetail;
    setOperateLogList(data);
  };

  const arrowIcon = ({ operateType: type, showDetail }, index) => {
    switch (type) {
      case LOG_TYPE.REMOVE:
      case LOG_TYPE.SUCCESS:
      case LOG_TYPE.FAIL:
        break;
      default:
        return (
          <img
            className={styles.arrow}
            src={showDetail ? upHide : downShow}
            onClick={() => changeShowDetail(index)}
          />
        );
    }
  };

  const itemContentRender = ({
    operateType: type,
    hourOrderInfos,
    units,
    successUnits,
    failUnits,
    timelySubmitTime,
  }) => {
    let {
      REMOVE,
      SUCCESS,
      FAIL,
      CREATE,
      MODIFY_CONTENT,
      SUBMIT,
      TIMELY_SUBMIT,
      MODIFY_UNIT,
      PART_SUCCESS,
      TIMELY,
      CANCEL_TIMELY,
    } = LOG_TYPE;
    switch (type) {
      case REMOVE:
      case SUCCESS:
      case FAIL:
        <div />;
      case MODIFY_CONTENT:
      case SUBMIT:
      case TIMELY_SUBMIT:
        return (
          <Table
            className={styles.table}
            dataSource={hourOrderInfos}
            rowKey="hourOrder"
            bordered={true}
            locale={tableLocale}
            pagination={false}
          >
            <Column title="时点" align="center" dataIndex="hourOrder" key="hourOrder" />
            <Column
              align="center"
              title="交易方向"
              dataIndex="tradeStrategyType"
              key="tradeStrategyType"
              render={detailTableTradeTypeContentRender}
            />
            <Column
              align="center"
              title="申报电量"
              dataIndex="power"
              key="power"
              render={detailTableSubmitPowerContentRender}
            />
            <Column
              align="center"
              title="申报电价"
              dataIndex="price"
              key="price"
              render={(text) => <>{text.toFixed(2)}元/MWh</>}
            />
          </Table>
        );
      case MODIFY_UNIT:
      case CREATE:
        return <> {units.join('、')}</>;
      case PART_SUCCESS:
        return (
          <>
            <div className={styles.successUnits}>
              <span className={styles.label}>成功{successUnits?.length}</span>
              <span className={styles.list}>{successUnits?.join('、')}</span>
            </div>
            <div className={styles.failUnits}>
              <span className={styles.label}>失败{failUnits?.length}</span>
              <span className={styles.list}>{failUnits?.join('、')}</span>
            </div>
          </>
        );
      case TIMELY:
        return <>定时申报时间：{moment(timelySubmitTime).format('YYYY.MM.DD HH:mm')}</>;
      case CANCEL_TIMELY:
        return <>原定时申报时间：{moment(timelySubmitTime).format('YYYY.MM.DD HH:mm')}</>;
    }
  };

  /**
   * 方案详情交易方向列渲染
   * @param {*} strategy
   * @returns
   */
  const detailTableTradeTypeContentRender = (strategy) => {
    let { SELL, BUY, NOT_DEAL, NO_STRATEGY } = TRADE_STRATEGY;
    switch (strategy) {
      case SELL:
        return <span>卖出</span>;
      case BUY:
        return <span>买入</span>;
      case NOT_DEAL:
        return <span>不交易</span>;
      case NO_STRATEGY:
        return <span>无策略</span>;
    }
  };

  /**
   * 方案详情申报电量列渲染
   * @param {*} text
   * @param {*} record
   * @returns
   */
  const detailTableSubmitPowerContentRender = (text, record) => {
    let { FIXED, INSTALLED_CAPACITY, TRADE_LIMIT } = SUBMIT_TYPE;
    switch (record.submitType) {
      case FIXED:
        return <>{text.toFixed(3)}MWh</>;
      case INSTALLED_CAPACITY:
        return <>装机容量*{Math.round(text * 100)}%</>;
      case TRADE_LIMIT:
        return <>交易限额*{Math.round(text * 100)}%</>;
    }
  };

  /**
   * 渲染抽屉title
   * @returns
   */
  const drawerTitleRender = () => (
    <div className={styles.modalTitle}>
      <img src={operateLogModal} />
      <span className={styles.text}>操作日志</span>
    </div>
  );
  /**
   * 渲染不同方案的tab签
   * @returns
   */
  const tabItemRender = () =>
    programList.map(({ status, title, id }) => (
      <TabPane
        tab={status !== PROGARM_STATUS.DEL ? title : <span className="isDeleted">{title}</span>}
        key={id}
      />
    ));

  return (
    <Drawer
      className={styles.operateLogModal}
      title={drawerTitleRender()}
      width={612}
      footer={null}
      visible={showOperateLog}
      onClose={() => setShowOperateLog(false)}
    >
      <Tabs activeKey={tabActiveKey} onChange={(key) => fetchOperateLogsFunc(key)}>
        {tabItemRender()}
      </Tabs>
      <Spin spinning={loading}>
        <div className={styles.content}>
          {operateLogList.map((item, index) => (
            <div className={`${styles.item} ${item.showDetail ? styles.show : ''}`} key={index}>
              <div className={styles.itemHeader}>
                <div className={styles.left}>
                  {index === 0 ? <img src={selectedCircle} /> : <div className={styles.circle} />}
                  <span className={styles.dateTime}>
                    {moment(item.operateTime).format('YYYY.MM.DD HH:mm:ss')}
                  </span>
                  <span className={styles.operateType}>{LOG_TYPE_CN[item.operateType]}</span>
                  {arrowIcon(item, index)}
                </div>

                <div className={styles.right}>
                  <span className={styles.label}>操作人：</span>
                  <span className={styles.value}>{item.operateUserName}</span>
                </div>
              </div>
              <div className={styles.itemContent}>{itemContentRender(item)}</div>
            </div>
          ))}
        </div>
      </Spin>
    </Drawer>
  );
}

export default connect(
  ({
    rollingBatch: {
      globalSequence: {
        current: { tradeSequenceId: currentSequenceId },
      },
      currentProgramInfo: { id: currentProgramId },
    },
  }) => ({ currentSequenceId, currentProgramId }),
  null,
  null,
  { forwardRef: true },
)(forwardRef(OperateLogModal));
